<template>
  <div class="appchart">
    <div :id="id" :ref="id" class="charts"></div>
  </div>
</template>

<script>
let num = 1;
import * as echarts from "echarts";
import { loopShowTooltip } from "./echartTooltip.js";
export default {
  name: "AppChart",
  props: {
    option: {
      type: Object,
      require: true,
    },
    showAutoTooltip: {
      type: Boolean,
      default: false,
    },
    delayTime: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      id: `chart-` + num,
      chart: null,
      resizeFn: null,
      chartTooltip: null,
    };
  },
  watch: {
    option: {
      deep: true,
      // immediate: true,
      handler: function (val) {
        this.chart.setOption(val, true);
        if (this.showAutoTooltip) {
          this.chartTooltip?.clearLoop();
          this.chartTooltip = null;
          this.chartTooltip = loopShowTooltip(this.chart, this.option, {
            loopSeries: true,
          });
        }
      },
    },
  },
  created() {
    ++num;
  },
  mounted() {
    let self = this;
    this.init();
    this.resizeFn = function () {
      self.$nextTick(() => {
        setTimeout(() => {
          self.chart?.resize();
        }, self.delayTime);
      });
    };
    window.addEventListener("resize", this.resizeFn, false);
  },
  beforeDestroy() {
    // 销毁
    this.chartTooltip?.clearLoop();
    this.chart?.dispose();
    window.removeEventListener("resize", this.resizeFn, false);
  },
  methods: {
    // 初始化
    init() {
      this.chart = echarts.init(this.$refs[this.id]);
      this.chart.setOption(this.option, true);

      if (this.showAutoTooltip) {
        this.chartTooltip?.clearLoop();
        this.chartTooltip = null;
        this.chartTooltip = loopShowTooltip(this.chart, this.option, {
          loopSeries: true,
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.appchart {
  width: 100%;
  height: 100%;

  .charts {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
  }
}
</style>
